package com.dapeng.jackson.serializer;

import com.dapeng.jackson.abstracts.BaseJKAnnotationSerializer;
import com.dapeng.jackson.annotations.JKPercentFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @BelongProject study
 * @BelongPackage com.dapeng.jackson.serializer
 * @Description TODO
 * @ClassName JKPercentFormatSerializer
 * @Author xupenghong
 * @Date 2024/9/13 16:06
 * @Version 1.0.0
 */
public class JKPercentFormatSerializer extends BaseJKAnnotationSerializer<JKPercentFormat, Number> {

    @Override
    public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            return;
        }

        BigDecimal bigValue;
        if (value instanceof BigDecimal) {
            bigValue = (BigDecimal) value;
        } else if (value instanceof Float) {
            bigValue = BigDecimal.valueOf((Float) value);
        } else if (value instanceof Double) {
            bigValue = BigDecimal.valueOf((Double) value);
        } else if (value instanceof Long) {
            bigValue = BigDecimal.valueOf((Long) value);
        } else if (value instanceof Integer) {
            bigValue = BigDecimal.valueOf((Integer) value);
        } else {
            gen.writeString(value.toString());
            return;
        }

        int scale = this.annotation.scale();
        boolean withSymbol = this.annotation.withSymbol();
        bigValue = bigValue.multiply(new BigDecimal(100)).setScale(scale, RoundingMode.HALF_UP);

        String plainString = bigValue.toPlainString();

        if (withSymbol && StringUtils.isNotEmpty(plainString)) {
            gen.writeString(plainString + "%");
        } else {
            gen.writeNumber(bigValue);
        }
    }
}
